var ws = require("nodejs-websocket");


var offer_client = null;
var answer_client = null;


function checkStart() {
  if (offer_client && answer_client) {
    offer_client.send(JSON.stringify({
      type: "create_offer"
    }))
  }
}

ws.createServer(function (conn) {
  // 收到websocket连接
  conn.on("text", function (str) {
    let obj = JSON.parse(str);
    console.log("recv:", obj);
    if ("connect" === obj.type) {
      if (!offer_client) {
        offer_client = conn;
        conn.send(JSON.stringify({
          type: "connect",
          code: 200,
          message: 'connect success'
        }))
        checkStart();
      } else if (!answer_client) {
        answer_client = conn;
        conn.send(JSON.stringify({
          type: "connect",
          code: 200,
          message: 'connect success'
        }))
        checkStart();
      } else {
        conn.send(JSON.stringify({
          type: "connect",
          code: -1,
          message: 'connect failed'
        }))
        conn.close();
      }
    } else if ("offer" === obj.type) {
      answer_client.send(str);
    } else if ("answer" === obj.type) {
      offer_client.send(str);
    } else if ("offer_ice" === obj.type) {
      answer_client.send(str);
    } else if ("answer_ice" === obj.type) {
      offer_client.send(str);
    }
  })

  conn.on("error", function (event) {

  });

  conn.on("close", function (code, reason) {
    if (conn === offer_client) {
      console.log("remove offer_client")
      offer_client = null;
    } else if (conn === answer_client) {
      console.log("remove answer_client")
      answer_client = null;
    }
  })
}).listen(9000);


